package cn.hlyc.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
public class CheckTokenGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.有order 就放行
        if (request.getURI().getPath().indexOf("order")>0) {
            return chain.filter(exchange);
        }

        //2.判断请求中是否有token  如果没有那么需要拦截
        //先拿token
        List<String> token = request.getHeaders().get("token");
        //判断token是否为空
        if (CollectionUtils.isEmpty(token)) {
            //如果是空的话 那么需要返回结果
            //这个对象是用来往response里面放的
            String result = "token为空  滚回去!!!";
            try {
                byte[] resultByteArray = result.getBytes("utf-8");
                //这个又是一个固定写法  就是往response里面写返回结果的
                DataBuffer dataBuffer = response.bufferFactory().wrap(resultByteArray);
                //设置返回的结果的字符集
                response.getHeaders().set("Content-Type","application/json;charset=utf-8");
                //如果是空的话那么就拦截
                //just()里面需要传的  就是需要返回的结果
                return response.writeWith(Mono.just(dataBuffer));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
